﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading;

namespace Niknak.Services.ServiceCore.Wcf
{
    public class Helper<ConfigurationSettings, WcfClient> 
        where ConfigurationSettings : IWcfConfig, new()
        where WcfClient : ICommunicationObject, IPingable, new()
    {
        private static AvailabilityStatus _AvailabilityStatus;

        public static ConfigurationSettings Settings
        {
            get { return new ConfigurationSettings(); }
        }

        public static bool EndpointAvailable
        {
            get 
            {
                if (_AvailabilityStatus == null || _AvailabilityStatus.CheckDate.AddSeconds(Settings.AvailabilityCheckTTL) < DateTime.UtcNow)
                    _AvailabilityStatus = new AvailabilityStatus()
                    {
                        CheckDate = DateTime.UtcNow,
                        IsAvailable = Ping() == "PONG"
                    };

                return _AvailabilityStatus.IsAvailable;
            }
        }

        internal static string Ping()
        {
            WcfClient client = new WcfClient();
            try
            {
                Trace.TraceInformation("PING");
                string value = client.Ping();
                client.Close();
                return value;
            }
            catch (Exception ex)
            {
                ex.GetHashCode();
                client.Abort();
            }

            return string.Empty;
        }

        private class AvailabilityStatus
        {
            public DateTime CheckDate { get; set; }
            public bool IsAvailable { get; set; }
        }
    }
}
